package com.tc.zigbee.mt;

import java.io.IOException;
import java.io.InputStream;
public class MtCommand {
	public byte length;
	public byte cmd0;
	public byte cmd1;
	public byte[] command;

	public byte xor;
	public byte[] frame;
	public void fillFrame(){
		frame = toframe();
		xor = xor(frame);
	}
	byte[] toframe(){
		byte[] f = new byte[length + 5];

		f[0] = (byte)0xfe;
		f[1] = length;
		f[2] = cmd0;
		f[3] = cmd1;
		for(int i = 0; i < command.length; i++)
			f[i + 4] = command[i];
		f[f.length - 1] = xor(f);
		return f;
	}
	public byte[] read(InputStream in) throws IOException{
		byte hh = (byte)in.read();

		if(hh != (byte)0xfe){
			throw new IOException("串口返回数据格式错误！");
		}
		length = (byte)in.read();
		cmd0 = (byte)in.read();
		cmd1 = (byte)in.read();
		command = new byte[length];
		int start = 0;
		while(start != length){
			int rl = in.read(command, start, command.length - start);
			start += rl;

		}


		xor = (byte)in.read();
		frame = toframe();
		byte mxor = xor(frame);
		assert(mxor == xor);
		return frame;
	}
	byte xor(byte[] f){
		byte base = f[1];
		for(int i = 2; i < f.length - 1; i++)
			base ^= f[i];
		return base;
	}


}
